package com.phonetools.commonutils.file

import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.util.*

/**
 * ini文件解析
 */
class IniReader @Throws(IOException::class) private constructor(fileName: String) {
    var sections = HashMap<String, Properties>()

    @Transient
    var lastProperties: Properties? = null

    companion object {
        /**
         * 解析ini文件内容
         */
        @Throws(IOException::class)
        fun parse(fileName: String): IniReader {
            return IniReader(fileName)
        }
    }

    init {
        val reader = BufferedReader(FileReader(fileName))
        read(reader)
        reader.close()
    }

    /**
     * 读取ini文件
     */
    @Throws(IOException::class)
    private fun read(reader: BufferedReader) {
        reader.forEachLine {
            parseLine(it)
        }
    }

    /**
     * 逐行解析ini配置文件
     */
    private fun parseLine(inputLine: String) {
        val line = inputLine.trim()
        if (line.matches(Regex("\\[.*\\]"))) {
            val section = line.replaceFirst(Regex("\\[(.*)\\]"), "$1")
            val properties = Properties()
            sections[section] = properties
            lastProperties = properties
        } else if (line.matches(Regex(".*=.*"))) {
            val properties = lastProperties
            if (properties != null) {
                val i = line.indexOf('=')
                val name = line.substring(0, i).trim()
                val value = line.substring(i + 1).trim()
                properties[name] = value
            }
        }
    }

    /**
     * 获取ini文件中的值
     */
    fun getValue(section: String, name: String): String? {
        return sections[section]?.getProperty(name)
    }

    /**
     * 判断是否存在key标签
     */
    fun containsKey(section: String, key: String): Boolean {
        return sections[section]?.contains(key) ?: false
    }
}
